package com.cyj.redischarts.cyj.service.impl;

import com.alibaba.fastjson.JSON;
import com.cyj.redischarts.cyj.service.ChartsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.Set;

@Transactional
@Service
public class ChartsServiceImpl implements ChartsService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public static final String student = "student";

    @Override
    public String list() {

        Set<ZSetOperations.TypedTuple<String>> rangeWithScores = redisTemplate.opsForZSet().reverseRangeWithScores(student, 0, -1);
        System.out.println("获取到的排行和分数列表:" + JSON.toJSONString(rangeWithScores));

        return JSON.toJSONString(rangeWithScores);
    }

    @Override
    public Long add(String name, Double score) {
        Set<ZSetOperations.TypedTuple<String>> tuples = new HashSet<>();

        DefaultTypedTuple<String> tuple = new DefaultTypedTuple<>(name, score);
        tuples.add(tuple);

        Long num = redisTemplate.opsForZSet().add(student, tuples);
        System.out.println(num);
        return num;
    }

    @Override
    public Long count(Double score1, Double score2) {
        Long count = redisTemplate.opsForZSet().count(student, score1, score2);
        return count;
    }

    @Override
    public Long sum() {
        Long num = redisTemplate.opsForZSet().zCard(student);
        return num;
    }
}
